package net.guerlab.sdk.dingtalk.storage;

import lombok.Data;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 钉钉配置储存接口-内存实现
 *
 * @author guer
 */
@Data
public class DingTalkConfigMemoryStorage implements DingTalkConfigStorage {

    /**
     * accessToken
     */
    protected volatile String accessToken;

    /**
     * 过期时间，单位秒
     */
    protected volatile long expiresTime;

    /**
     * 企业ID
     */
    protected volatile String corpId;

    /**
     * appKey
     */
    protected volatile String appKey;

    /**
     * appSecret
     */
    protected volatile String appSecret;

    /**
     * accessToken可重入锁
     */
    protected Lock accessTokenLock = new ReentrantLock();

    @Override
    public boolean isAccessTokenExpired() {
        return System.currentTimeMillis() > this.expiresTime;
    }

    @Override
    public void expireAccessToken() {
        this.expiresTime = 0;
    }

    @Override
    public void updateAccessToken(String accessToken, long expiresInSeconds) {
        this.accessToken = accessToken;
        this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L;
    }
}
